package ru.demo.abstarctservice.adapter.rabbit;

import org.springframework.amqp.core.*;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Configuration
@EnableConfigurationProperties(RabbitMQProperties.class)
public class RabbitMQConfiguration {

    @Bean
    public TopicExchange exchange(RabbitMQProperties properties) {
        return new TopicExchange(properties.getChangesExchange(), true, false);
    }

    @Bean
    public Queue serviceUpdateQueue() {
        return new Queue("abstract-service");
    }

    @Bean
    public Declarables bindings(RabbitMQProperties properties) {
        if (properties.getBindings() == null)
            return null;
        List<Binding> bindings = new ArrayList<>();
        TopicExchange topicExchange = new TopicExchange(properties.getChangesExchange(), true, false);
        for (Map.Entry<String, List<String>> entry : properties.getBindings().entrySet()) {
            bindings.addAll(entry.getValue().stream().map(
                    value -> BindingBuilder.bind(new Queue(entry.getKey())).to(topicExchange).with(value)
            ).toList());
        }
        return new Declarables(bindings);
    }

    @Bean
    public MessageConverter converter() {
        Jackson2JsonMessageConverter converter = new Jackson2JsonMessageConverter();
        converter.setAlwaysConvertToInferredType(true);
        return converter;
    }

}
